#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys

sys.path.append("/work/opt/analytic/my_python")
from lib.format_time import *
from lib.HandleMysql import *
from lib.handle_mongo import *
from lib.switch_code import *
from lib.load_data import *
from topinfo_conn import *
from base_dict import *
from pmc_order import *
import re
import time

reload(sys)
sys.setdefaultencoding('utf-8')


# get topinfo from zhiding DB
def load_topinfo(date):
    print 'get topinfo data begin'
    conn = top_conn()
    stat_conn = zhiding_conn()
    order_conn = wuba58_conn()
    stat_table = "topinfo_income"
    line_list = []
    query = "select topinfoid,topid,userid,toptype,cateid,localid,tophour,starttime,endtime,addtime,state,amount,topsortid,payamount,sethour,infoid from topinfo_topinfo where date(addtime)='%s' and toptype not in (4,6) order by topinfoid asc" % date
    #print query
    items = conn.get_results(query)
    print "topinfo lenght : %s" % len(items)
    for item in items:
        top_info_id = item[0]
        top_id = item[1]
        user_id = item[2]
        top_type = item[3]
        cate_id = item[4]
        city = item[5]
        top_hour = item[6]
        start_time = item[7]
        end_time = item[8]
        add_time = item[9]
        state = item[10]
        amount = item[11]
        top_sortid = item[12]
        pay_amount = item[13]
        set_hour = item[14]
        info_id = item[15]
        city_name = ''
        area_name = ''
        local_name = ''

        query_in = "select infoid from topinfo_infolog where topid=%s" % top_id
        items_in = conn.get_results(query_in)
        if len(items_in) > 0:
            info_id = items_in[0][0]

        dc = get_citys(city)
        if dc != None:
            if len(dc) > 0:
                city_name = dc[0][1]
            if len(dc) > 1:
                area_name = dc[1][1]
            if len(dc) > 2:
                local_name = dc[2][1]

        dc = get_cates(cate_id)
        cat1name = ''
        cat2name = ''
        if dc != None:
            if len(dc) > 0:
                cat1name = dc[0][1]
            if len(dc) > 1:
                cat2name = dc[1][1]
        print cat1name

        query = 'select count(1) from order_info where order_state in (35,45,50) and user_id = %s' % user_id
        its = order_conn.get_results(query)
        # is vip 
        user_type = its[0][0]
        if user_type > 0:
            user_type = 1

        cash_amount = 0.0
        discount_amount = 0.0

        q = "select ifnull(cash_amount-refund_cash_amount,0),ifnull(discount_amount-refund_discount_amount,0) from top_info_pay where top_info_id=%s" % top_info_id
        its = order_conn.get_results(q)
        if len(its) > 0:
            cash_amount = its[0][0]
            discount_amount = its[0][1]

        param = ["%s" % date, "%s" % top_id, "%s" % top_info_id, "0", "%s" % info_id, "%s" % user_id, "%s" % user_type,
                 "%s" % add_time, city_name, area_name, cat1name, cat2name, "%s" % top_type, "%s" % start_time,
                 "%s" % end_time, "%s" % amount, "%s" % pay_amount, "%s" % state, "%s" % cash_amount,
                 "%s" % discount_amount]
        line_list.append('\001'.join(param))

    cont = '\n'.join(line_list)
    path = "/work3/opt/analytic/data/topinfo/"
    file_name = "top_info_income_%s.txt" % date.replace('-', "")
    writeTextToFile(path, file_name, "w", cont)
    q = "delete from %s where top_type not in (4,6) and stat_date = '%s'" % (stat_table, date)
    stat_conn.execute_sql(q)
    load_data(stat_conn, path + file_name, stat_table, '\001')
    conn.close()
    stat_conn.close()
    order_conn.close()
    print "%s : done" % date


# get topinfo project from topinfo DB
def load_topinfo_project(date):
    print 'get topinfo project data begin'
    conn = top_conn()
    stat_conn = zhiding_conn()
    order_conn = wuba58_conn()
    stat_table = "topinfo_income"
    line_list = []
    query = "select projectid,topid,infoid,userid,type,cateid,localid,projecttime,endtime,state,allconsume,payconsume,createtime from topinfo_project where date(createtime)='%s' order by projectid asc" % date
    #print query
    items = conn.get_results(query)
    print "topinfo project lenght : %s" % len(items)
    for item in items:
        projectid = item[0]
        top_id = item[1]
        user_id = item[2]
        info_id = item[3]
        ptype = item[4]
        cate_id = item[5]
        city = item[6]
        start_time = item[7]
        end_time = item[8]
        state = item[9]
        add_time = item[9]
        amount = item[10]
        pay_amount = item[11]
        add_time = item[12]
        city_name = ''
        area_name = ''
        local_name = ''

        dc = get_citys(city)
        #print city
        if dc != None:
            if len(dc) > 0:
                city_name = dc[0][1]
            if len(dc) > 1:
                area_name = dc[1][1]
            if len(dc) > 2:
                local_name = dc[2][1]

        dc = get_cates(cate_id)
        cat1name = ''
        cat2name = ''
        if dc != None:
            if len(dc) > 0:
                cat1name = dc[0][1]
            if len(dc) > 1:
                cat2name = dc[1][1]

        query = 'select count(1) from order_info where order_state in (35,45,50) and user_id = %s' % user_id
        its = order_conn.get_results(query)
        # is vip 
        user_type = its[0][0]
        if user_type > 0:
            user_type = 1

        money = get_topinfo_project_order_info(projectid, date)
        cash_amount = money.split(',')[0]
        discount_amount = money.split(',')[1]

        top_type = 4
        if ptype == 1:
            top_type = 6

        param = ["%s" % date, "%s" % top_id, "0", "%s" % projectid, "%s" % info_id, "%s" % user_id, "%s" % user_type,
                 "%s" % add_time, city_name, area_name, cat1name, cat2name, "%s" % top_type, "%s" % start_time,
                 "%s" % end_time, "%s" % amount, "%s" % pay_amount, "%s" % state, "%s" % cash_amount,
                 "%s" % discount_amount]
        line_list.append('\001'.join(param))

    cont = '\n'.join(line_list)
    path = "/work3/opt/analytic/data/topinfo/"
    file_name = "top_info_income_project_%s.txt" % date.replace('-', "")
    writeTextToFile(path, file_name, "w", cont)
    q = "delete from %s where top_type in (4,6) and stat_date = '%s'" % (stat_table, date)
    print q
    stat_conn.execute_sql(q)
    load_data(stat_conn, path + file_name, stat_table, '\001')
    conn.close()
    stat_conn.close()
    print "%s : done" % date


def execute(date, inp):
    try:
        load_topinfo(date)
    except Exception, e:
        print 'get_order_info:', e
    try:
        load_topinfo_project(date)
    except Exception, e:
        print 'load_topinfo_project:', e


def main():
    inp = "0"
    if len(sys.argv) == 1:
        start_date = get_yesterday()
        end_date = start_date
    elif len(sys.argv) == 2:
        start_date = format_date(sys.argv[1])
        end_date = start_date
    elif len(sys.argv) == 3:
        start_date = format_date(sys.argv[1])
        end_date = format_date(sys.argv[2])
    stat_date = start_date
    while stat_date >= start_date and stat_date <= end_date:
        print "The program of the date of %s is beginning at %s " % (stat_date, get_now())
        execute(stat_date, inp)
        print "The program of the date of %s is end at %s " % (stat_date, get_now())
        stat_date = var_date(stat_date)


if __name__ == '__main__':
    main()
